package com.fasttreatment.zzr.demo.activity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;

import com.android.androidlibrary.base.BaseActivity;
import com.fasttreatment.zzr.demo.R;
import com.hyphenate.EMCallBack;
import com.hyphenate.EMMessageListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMCmdMessageBody;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.chat.EMTextMessageBody;
import com.hyphenate.easeui.domain.EaseEmojicon;
import com.hyphenate.easeui.widget.EaseChatInputMenu;
import com.hyphenate.easeui.widget.EaseChatMessageList;
import com.hyphenate.easeui.widget.EaseVoiceRecorderView;

import java.util.List;

import butterknife.BindView;


/**
 * Created by zzr on 2017/2/6.
 */

public class ChatActivity extends BaseActivity implements EMMessageListener {

    public static final String CHATID = "chatId";
    @BindView(R.id.toolbar_title_tv)
    TextView title;
    @BindView(R.id.ec_text_content)
    TextView mEcTextContent;
    @BindView(R.id.input_menu)
    EaseChatInputMenu mInputMenu;
    @BindView(R.id.voice_recorder)
    EaseVoiceRecorderView mVoiceRecorder;
//    @BindView(R.id.message_list)
//    EaseChatMessageList mMessageList;


    // 当前聊天的 ID
    private String chatId;
    // 消息监听器
    private EMMessageListener mMessageListener;
    // 当前会话对象
    private EMConversation mConversation;
    protected ListView listView;

    @Override
    public void initData(Bundle savedInstanceState) {
        mInputMenu.init(null);
//      listView= mMessageList.getListView();
        initView();
        initConversation();
    }


    public void sendTextMessage(String content) {

        if (!TextUtils.isEmpty(content)) {
            // 创建一条新消息，第一个参数为消息内容，第二个为接受者username
            EMMessage message = EMMessage.createTxtSendMessage(content, chatId);
            // 将新的消息内容和时间加入到下边
            mEcTextContent.setText(mEcTextContent.getText() + "\n发送：" + content + " - time: " + message.getMsgTime());
            // 调用发送消息的方法
            EMClient.getInstance().chatManager().sendMessage(message);
            // 为消息设置回调
            message.setMessageStatusCallback(new EMCallBack() {
                @Override
                public void onSuccess() {
                    // 消息发送成功，打印下日志，正常操作应该去刷新ui
                    Log.i("zzr", "send message on success");
                }

                @Override
                public void onError(int i, String s) {
                    // 消息发送失败，打印下失败的信息，正常操作应该去刷新ui
                    Log.i("zzr", "send message on error " + i + " - " + s);
                }

                @Override
                public void onProgress(int i, String s) {
                    // 消息发送进度，一般只有在发送图片和文件等消息才会有回调，txt不回调
                }
            });
        }
    }

    @Override
    public void setListener() {
        mInputMenu.setChatInputMenuListener(new EaseChatInputMenu.ChatInputMenuListener() {
            @Override
            public void onSendMessage(String content) {
                sendTextMessage(content);
            }

            @Override
            public void onBigExpressionClicked(EaseEmojicon emojicon) {

            }

            @Override
            public boolean onPressToSpeakBtnTouch(View v, MotionEvent event) {
                return mVoiceRecorder.onPressToSpeakBtnTouch(v, event, new EaseVoiceRecorderView.EaseVoiceRecorderCallback() {
                    @Override
                    public void onVoiceRecordComplete(String voiceFilePath, int voiceTimeLength) {
                        EMMessage message = EMMessage.createVoiceSendMessage(voiceFilePath, voiceTimeLength, chatId);
                    }
                });
            }
        });
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_chat;
    }


    private void initView() {
        chatId = getIntent().getStringExtra(CHATID);
        mMessageListener = this;
        title.setText(chatId);
        mEcTextContent.setMovementMethod(new ScrollingMovementMethod());
    }

    private void initConversation() {
        /**
         * 初始化会话对象，这里有三个参数么，
         * 第一个表示会话的当前聊天的 useranme 或者 groupid
         * 第二个是绘画类型可以为空
         * 第三个表示如果会话不存在是否创建
         */
        mConversation = EMClient.getInstance().chatManager().getConversation(chatId, null, true);
        // 设置当前会话未读数为 0
        mConversation.markAllMessagesAsRead();
        int count = mConversation.getAllMessages().size();
        if (count < mConversation.getAllMsgCount() && count < 20) {
            // 获取已经在列表中的最上边的一条消息id
            String msgId = mConversation.getAllMessages().get(0).getMsgId();
            // 分页加载更多消息，需要传递已经加载的消息的最上边一条消息的id，以及需要加载的消息的条数
            mConversation.loadMoreMsgFromDB(msgId, 20 - count);
        }
        // 打开聊天界面获取最后一条消息内容并显示
        if (mConversation.getAllMessages().size() > 0) {
            EMMessage messge = mConversation.getLastMessage();
            EMTextMessageBody body = (EMTextMessageBody) messge.getBody();
            // 将消息内容和时间显示出来
            mEcTextContent.setText("聊天记录：" + body.getMessage() + " - time: " + mConversation.getLastMessage().getMsgTime());
        }
    }

    /**
     * 自定义实现Handler，主要用于刷新UI操作
     */
    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    EMMessage message = (EMMessage) msg.obj;
                    EMTextMessageBody body = (EMTextMessageBody) message.getBody();
                    // 将新的消息内容和时间加入到下边
                    mEcTextContent.setText(mEcTextContent.getText() + "\n接收：" + body.getMessage() + " - time: " + message.getMsgTime());
                    break;
            }
        }
    };

    @Override
    protected void onResume() {
        super.onResume();
        // 添加消息监听
        EMClient.getInstance().chatManager().addMessageListener(mMessageListener);
    }

    @Override
    protected void onStart() {
        super.onStart();
        // 移除消息监听
        EMClient.getInstance().chatManager().removeMessageListener(mMessageListener);
    }

    //环信消息监听主要方法

    /**
     * 收到新消息
     *
     * @param list 收到的新消息集合
     */
    @Override
    public void onMessageReceived(List<EMMessage> list) {
        // 循环遍历当前收到的消息
        for (EMMessage message : list) {
            if (message.getFrom().equals(chatId)) {
                // 设置消息为已读
                mConversation.markMessageAsRead(message.getMsgId());

                // 因为消息监听回调这里是非ui线程，所以要用handler去更新ui
                Message msg = mHandler.obtainMessage();
                msg.what = 0;
                msg.obj = message;
                mHandler.sendMessage(msg);
            } else {
                // 如果消息不是当前会话的消息发送通知栏通知
            }
        }

    }

    /**
     * 收到新的 CMD 消息
     *
     * @param list
     */
    @Override
    public void onCmdMessageReceived(List<EMMessage> list) {
        for (int i = 0; i < list.size(); i++) {
            // 透传消息
            EMMessage cmdMessage = list.get(i);
            EMCmdMessageBody body = (EMCmdMessageBody) cmdMessage.getBody();
            Log.i("lzan13", body.action());
        }
    }

    /**
     * 收到新的已读回执
     *
     * @param list
     */
    @Override
    public void onMessageRead(List<EMMessage> list) {

    }

    /**
     * 收到新的发送回执
     *
     * @param list
     */
    @Override
    public void onMessageDelivered(List<EMMessage> list) {

    }

    /**
     * 消息的状态改变
     *
     * @param emMessage 发生改变的消息
     * @param o         包含改变的消息
     */
    @Override
    public void onMessageChanged(EMMessage emMessage, Object o) {

    }


}
